<?php
error_reporting(E_ERROR);
define("USERAGENT", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5");

/* 
说明：种子搜索类
创建：2012-08-08
修改：2012-08-14
*/
class torrentSearch
{
	// 当前搜索关键字
	public $searchkey = "";
	public $roothosts = array();
	public $hosts = array();
	public $hostid = 0;
	public $host = null;
	public $searchurl = "torrentrss.php?rows=\$rows&ismalldescr=1&search=\$key&search_mode=1";
	public $searchpage = array();
	public $torrents = array();
	public $rows = 1;
	public $hostisload=false;

	// 构造函数
	function __construct($key,$rows,$hostid)
	{
		/*
		if ($host)
		{
			$host = iconv("GBK","UTF-8",$host);
			$arr = explode("|",$host);
			if (count($arr)==1)
				$arr[]=$arr[0];
			$this->hosts[]=json_decode('{"name":"'.$arr[1].'","url":"'.$arr[0].'"}');
//			echo "name:".$this->hosts[0]->name;
			$this->hostisload=true;
		}
		*/
		$this->readconfig();
		if (!is_null($hostid))
		{
			$this->host=$this->roothosts[(int)$hostid];
		}
      $this->searchkey = $key;
		if ($rows>0)
			$this->rows = $rows;
   }

	// 加载参数
	function readconfig()
	{
		$contents = file_get_contents("config.json");
		$json = json_decode(iconv("UTF-8","UTF-8",$contents));

		$this->searchpage = $json->searchpage;

		$contents = file_get_contents("hosts.json");
		$json = json_decode(iconv("UTF-8","UTF-8",$contents));
		$this->roothosts = $json->hosts;
	}

	// 开始查询(停用)
	public function searchall()
	{
		foreach ($this->roothosts as $host) {
			$url=$host->url;
			$searchs = array("\$rows","\$key");
			$replaces = array($this->rows,$this->searchkey);
			$xml = $this->geturlcontent($url.(str_replace($searchs,$replaces,$this->searchurl)));
			if ($xml!='')
			{
				$info = array("item"=>($this->parseSource($host->name,$xml)),"host"=>$host);
				$this->torrents[]=$info;
				$this->output($info);
			}
			else
			{
				echo "<div class='torrentlist'>$host->name search error.<br/></div>";
			}
		}
	}

	// 查询当前指定站
	public function search()
	{
		$host=$this->host;
		$url=$host->url;
		$searchs = array("\$rows","\$key");
		$searchurl = $this->searchurl;
		// 指定类型
		if (!is_null($host->type))
		{
			$searchurl = $this->searchpage[(int)$host->type]->url;
		}
		$replaces = array($this->rows,$this->searchkey);
		$xml = $this->geturlcontent($url.(str_replace($searchs,$replaces,$searchurl)));
		if ($xml!='')
		{
			$info = array("item"=>($this->parseSource($host->name,$xml)),"host"=>$host);
			$this->torrents[]=$info;
			$this->output($info);
		}
		else
		{
			echo "<div class='torrentlist'>$host->name search error.<br/></div>";
		}
	}

	private function output($info)
	{
		echo "<div class='torrentlist'>";
		echo "<table cellspacing='0' cellpadding='2'>";
		echo "<tr><td colspan='2'><span class='host'><a href='".$info["host"]->url."' target='_blank'>".$info["host"]->name."</a></span></td></tr>";
		$n=1;
		foreach ($info["item"] as $item) {
			echo "<tr>";
			echo "<td class='category' valign='top'>$n. [".$item["category"]."]<td>";
			echo "<td class='item'>";
			if ($item["downloadurl"])
				echo "<a href='".$item["downloadurl"]."' target='_blank' class='hostlistdownload' alt='download torrent' title='download torrent'><img src='download.gif'></a>";
			echo "<a href='".$item["link"]."' target='_blank' title=''>".$item["title"]."</a>";
			echo "<br/>[".$item["date"]."][".$item["author"]."]";
			if ($item["size"])
				echo "[".$item["size"]."]";
			echo "</td>";
			echo "</tr>";
			$n++;
		}
		if ($n==1)
		{
			echo "<tr><td colspan='2'>no items.</td></tr>";
		}
		echo "</table></div>";
	}

	private function geturlcontent($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		curl_setopt($ch, CURLOPT_USERAGENT, USERAGENT);
		curl_setopt($ch, CURLOPT_REFERER,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// 取消证书检测
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$r = curl_exec($ch);
		curl_close($ch);
		return $r;
	}

	// 解析XML数据
	private function parseSource($host,$xml)
	{
		$file = "temp".rand().".xml";
		file_exists($file) && unlink($file);
		$fp = @fopen($file, 'ab');
		rewind($fp);
		fwrite($fp, $xml);
		fflush($fp);
		ftruncate($fp, ftell($fp));
		if ($fp) @fclose($fp);

		$dom = new DOMDocument();
		$returnData = array();
		$isload = false;
		try {
			 $isload = $dom->load($file);
		} catch (Exception $e) {        // 捕获异常
		}

		if ($isload)
		{
			$items = $dom->getElementsByTagName("item");
			foreach($items as $item)
			{
				$arr = array("title"=>"","link"=>"","category"=>"","date"=>"","author"=>"","downloadurl"=>"","size"=>"");
				// 标题
				$arr["title"]=$item->getElementsByTagName("title")->item(0)->nodeValue;
				// 连接地址
				$arr["link"]=$item->getElementsByTagName("link")->item(0)->nodeValue;
				if ($item->getElementsByTagName("enclosure")->item(0))
				{
					// 种子文件地址
					$arr["downloadurl"]=$item->getElementsByTagName("enclosure")->item(0)->getAttribute("url");
					// 种子文件地址
					$arr["size"]=$this->mksize($item->getElementsByTagName("enclosure")->item(0)->getAttribute("length"));
				}
				// 目录
				$arr["category"]=$item->getElementsByTagName("category")->item(0)->nodeValue;
				// 发布人
				$author = $item->getElementsByTagName("author")->item(0)->nodeValue;
				if (ereg ("\((.+)\)", $author, $regs)) {
					$author=$regs[1];
				} else {
					$author="unknown";
				}

				$arr["author"]=$author;
				// 发布日期
				$arr["date"]=date('Y-m-d H:i:s',strtotime($item->getElementsByTagName("pubDate")->item(0)->nodeValue));
				$returnData[]=$arr;
			}
		}
		unlink($file);
		return $returnData;
	}

	function mksize($bytes)
	{
		if ($bytes < 1000 * 1024)
		return number_format($bytes / 1024, 2) . " KB";
		elseif ($bytes < 1000 * 1048576)
		return number_format($bytes / 1048576, 2) . " MB";
		elseif ($bytes < 1000 * 1073741824)
		return number_format($bytes / 1073741824, 2) . " GB";
		elseif ($bytes < 1000 * 1099511627776)
		return number_format($bytes / 1099511627776, 3) . " TB";
		else
		return number_format($bytes / 1125899906842624, 3) . " PB";
	}
}
$test = new torrentSearch($_GET["key"],$_GET["rows"],$_GET["hostid"]);
$test->search();
?>